package com.eqdd.yiqidian.ui;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.EditorInfo;

import com.eqdd.inputs.AndroidNextInputs;
import com.eqdd.inputs.WidgetAccess;
import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.nextinputs.ValueScheme;
import com.eqdd.yiqidian.LoginActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.bean.rebuild.CompanyInfoResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.service.JPushService;
import com.eqdd.yiqidian.service.PushCodeRefreshService;
import com.eqdd.yiqidian.service.RongyunService;
import com.eqdd.yiqidian.ui.gongneng.daka.DakaActivity;
import com.eqdd.yiqidian.utils.EncryptUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.HashMap;

public class LoginActivity extends BaseActivity {
    private LoginActivityCustom dataBinding;
    private User user;
    private AndroidNextInputs inputs;
    private WidgetAccess access;
    private ActionSheetDialog bottomChoose;
    private ActionSheetDialog bottomPassChoose;
    private Intent regist;
    private boolean isUp = false;
    private boolean isNotification;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        dataBinding.etUsername.setText(TextUtils.isEmpty((String) SPUtil.getParam(Config.ACCOUNT_LAST)) ? "" : (String) SPUtil.getParam(Config.ACCOUNT_LAST));
    }

    @Override
    public void initData() {
        isNotification = getIntent().getBooleanExtra(Config.IS_NOTIFICATION, false);
        user = GreenDaoUtil.getUser();
        if (user != null) {
            System.out.println(user);

            dataBinding.etUsername.setText(user.getUname());
            if (user.getAuthen() != 0) {
                enterMainActivity(false);
            }
        }
        inputs = new AndroidNextInputs();
        access = new WidgetAccess(this);
        inputs  // 必选，手机号
                .add(access.findEditText(R.id.et_username))
                .with(StaticScheme.Required())
                // 必选 ，密码8~18
                .add(access.findEditText(R.id.et_password))
                .with(StaticScheme.Required(), ValueScheme.RangeLength(8, 18));
        dataBinding.etPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
//                    if(inputsAccount.test()){
                if (dataBinding.etUsername.getText().toString().matches("^(\\+?\\d{2}-?)?1[34578]\\d{9}$")) {
                    dataBinding.btnLogin.setEnabled(true);

                    dataBinding.btnLogin.setText("手机号登录");
                } else if (dataBinding.etUsername.getText().toString().matches("^[a-zA-Z][a-zA-Z0-9_]{4,15}$")) {
                    dataBinding.btnLogin.setEnabled(true);

                    dataBinding.btnLogin.setText("易企点号登录");
                } else {
                    dataBinding.btnLogin.setEnabled(false);
                }
//                    }
            }
        });
        getCompany();
    }

    @Override
    public void setView() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        final int screenHeight = metrics.heightPixels;

        dataBinding.etPassword.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                loginRequest();
            }
            return true;
        });
        dataBinding.getRoot().getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect r = new Rect(); //该对象代表一个矩形（rectangle）
            dataBinding.llRoot.getWindowVisibleDisplayFrame(r); //将当前界面的尺寸传给Rect矩形
            int deltaHeight = screenHeight - r.bottom;  //弹起键盘时的变化高度，在该场景下其实就是键盘高度。
            if (deltaHeight > 350 * WindowUtil.csw / WindowUtil.width && !isUp) {
                //该值是随便写的，认为界面高度变化超过150px就视为键盘弹起。
                isUp = true;
                ValueAnimator animator = ValueAnimator.ofFloat(0, 100);
                animator.setInterpolator(new AccelerateDecelerateInterpolator());
                animator.setDuration(500);
                animator.addUpdateListener(animation -> {
                    float curValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = dataBinding.logo.getLayoutParams();
                    layoutParams.height = (int) (300 - (2.4 * curValue)) * WindowUtil.csw / WindowUtil.width;
                    layoutParams.width = (int) (400 - (3.2 * curValue)) * WindowUtil.csw / WindowUtil.width;
                    dataBinding.logo.setLayoutParams(layoutParams);
                });
                animator.start();


            } else if (deltaHeight < 350 * WindowUtil.csw / WindowUtil.width && isUp) {
                isUp = false;
                System.out.println("down" + deltaHeight);
                ValueAnimator animator = ValueAnimator.ofFloat(0, 100);
                animator.setDuration(500);
                animator.setInterpolator(new AccelerateDecelerateInterpolator());
                animator.addUpdateListener(animation -> {
                    float curValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = dataBinding.logo.getLayoutParams();
                    layoutParams.height = (int) (60 + (2.4 * curValue)) * WindowUtil.csw / WindowUtil.width;
                    layoutParams.width = (int) (80 + (3.2 * curValue)) * WindowUtil.csw / WindowUtil.width;
                    dataBinding.logo.setLayoutParams(layoutParams);
                });
                animator.start();
            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_login:
                loginRequest();
                break;
            case R.id.tv_register:
                regist = new Intent(this, RegistActivity.class);
                regist.putExtra(Config.MODE, Config.MODE_REGISTER);
                startActivity(regist);
                break;
            case R.id.tv_forget_pass:
                startActivity(GetPwdSendCheckCodeActivity.class);

//                showPassChoose();
                break;
            case R.id.tv_register_qiye:
                regist = new Intent(this, RegistActivity.class);
                regist.putExtra(Config.MODE, Config.MODE_REGISTER_QIYE);
                startActivity(regist);
                break;
        }
    }

    private void test() {
        startActivity(DakaActivity.class);
    }

    private void loginRequest() {
        String username = dataBinding.etUsername.getText().toString().trim();
        String pass = dataBinding.etPassword.getText().toString().trim();
        if (inputs.test()) {
            sendRequest(username, pass);
        }
    }

    private void showPassChoose() {
        if (bottomPassChoose == null) {
            bottomPassChoose = ChooseAlertView.getBottomChoose(this, "找回密码方式",
                    new String[]{"手机号找回", "邮箱找回", "身份证找回"},
                    (ob, position) -> {
                        System.out.println(position);
                        switch (position) {
                            case 1:
//                                Intent intent = new Intent(this, RegistActivity.class);
//                                intent.putExtra(Config.MODE, Config.MODE_PASS_FORGET);
                                startActivity(GetPwdSendCheckCodeActivity.class);
                                break;
                            case 2:
                                startActivity(EmailCheckActivity.class);
                                break;

                        }
                    }
            );
        }
        bottomPassChoose.show();
    }

    private void showChoose() {
        if (bottomChoose == null) {
            bottomChoose = ChooseAlertView.getBottomChoose(this, "游客不会记录信息", new String[]{"游客", "实名认证"},
                    (ob, position) -> {
                        System.out.println(position);
                        if (position == 1) {
                            enterMainActivity();
                        } else if (position == 2) {
                            startActivityForResult(MineAuActivity.class, null, Config.MINE_AU);
                        }
                    }
            );
        }
        bottomChoose.show();
    }

    private void sendRequest(final String username, final String pass) {
        HashMap<String, String> map = new HashMap<>();
        map.put("u1", username);
        map.put("u2", EncryptUtil.sha1(pass + "EQD"));
        OkGo.<HttpResult<User>>post(HttpConfig.BASE_URL + HttpConfig.LOGIN)
                .params(map)
                .execute(new DialogCallBack<HttpResult<User>>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult<User>> response) {
                        HttpResult<User> httpResult = response.body();
                        // ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            GreenDaoUtil.insert(httpResult.getItems());
                            SPUtil.setParam(Config.PASS, pass);
                            if (httpResult.getItems().getAuthen() == 0) {
                                showChoose();
                            } else {
                                enterMainActivity();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<HttpResult<User>> response) {
                        super.onError(response);

                    }
                });

    }

    private void getCompany() {
        if (user == null) {
            return;
        }
        OkGo.<HttpResult<CompanyInfoResultBean>>post(HttpConfig.BASE_URL + HttpConfig.GET_COM_SIMPLE_INFO)
                .params("comId", user.getCompanyId())
                .execute(new DialogCallBack<HttpResult<CompanyInfoResultBean>>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult<CompanyInfoResultBean>> response) {
                        HttpResult<CompanyInfoResultBean> httpResult = response.body();
                        if (httpResult.getStatus() == 200) {
                            CompanyInfoResultBean bean = httpResult.getItems();
                            GreenDaoUtil.insert(bean);
                        }
                    }
                });
    }

    private void enterMainActivity(boolean isAutoEnter) {
        user = GreenDaoUtil.getUser();

        System.out.println("开启各服务");
        System.out.println(user);
        startService(new Intent(LoginActivity.this, JPushService.class));
        startService(new Intent(LoginActivity.this, RongyunService.class));
        if (!isAutoEnter) {
            startService(new Intent(LoginActivity.this, PushCodeRefreshService.class));
        }
        startActivity(new Intent(LoginActivity.this, MainActivity.class));

        SPUtil.setParam(Config.ACCOUNT_LAST, user.getUname());
        finish();
    }

    private void enterMainActivity() {
        if (isNotification) {
            setResult(Config.LOGIN_BACK);
            finish();
        } else {
//            PayUtil.pay(this, "内容", "标题", "0.01", SystemClock.currentThreadTimeMillis() + "", SystemClock.currentThreadTimeMillis() + "");

            enterMainActivity(false);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Config.MINE_AU://个人认证
                if (resultCode == Config.SUCCESS) {//个人认证成功
                    enterMainActivity();
                }
                break;
        }
    }
}
